<template>
  <div class="page-list-live">
    <PageList>
      <template #header>轨迹回放</template>
      <template #filter>
        <ListFilter :form="topFilter" :key-list="keyList" style="z-index: 10;" :lath="'140px'" @search="handleSearch" @reset="resetHandle"></ListFilter>
      </template>
      <template #tab>
        <div class="tips">
          <el-button type="primary" style="z-index: 10;" icon="el-icon-video-play" @click="time">播放</el-button>
          <el-button type="primary" style="z-index: 10;" icon="el-icon-video-pause" @click="suspendHandler">暂停</el-button>
          <el-button type="primary" style="z-index: 10;" icon="el-icon-circle-close" @click="stopHandler">停止</el-button>
          <el-button type="primary" style="z-index: 10;" icon="el-icon-refresh" @click="resetPlayHandler">重新播放</el-button>
        </div>
      </template>
      <template #tips>
        <div>
          <div>
            当前时间：{{ prople.createdTime }}
            <!-- <el-input v-model="duration" style="width: 300px; z-index: 10;" :disabled="clickSwaitch" type="number" @change="timeValueHandler"></el-input> -->
            <!-- 最大不能超过 {{ listAry.length }} 秒 -->
          </div>
          <el-slider id="slider" ref="slider" v-model="value" style="z-index: 10;" :show-tooltip="false"></el-slider>
          <div class="divOne">
            <img v-if="imgSrc" class="mapImg" :src="imgSrc" alt />
            <!-- 基站覆盖范围 -->
            <template v-for="item in baseStationList">
              <el-popover
                v-if="baseStationList.length > 0"
                :key="item.index"
                placement="top-start"
                class="up"
                :style="{ left: item.x + 'px', top: item.y + 'px', zIndex: 10 }"
                trigger="hover"
              >
                <div class="labelDiv">
                  <span class="shallow">基站名称:</span>
                  <span class="deep">{{ item.name }}</span>
                </div>
                <div class="labelDiv">
                  <span class="shallow">区域:</span>
                  <span class="deep">{{ item.scro }}</span>
                </div>
                <div class="labelDiv">
                  <span class="shallow">基站类型:</span>
                  <span class="deep">{{ item.jztype === 1 ? '进基站' : item.jztype === 2 ? '出基站' : '其他基站' }}</span>
                </div>
                <!-- <div class="labelDiv">
                  <span class="shallow">是否是考勤机站:</span>
                  <span class="deep">{{ item.status ? '是': '否' }}</span>
                </div> -->
                <img slot="reference" :src="item.url" alt="基站" />
              </el-popover>
              <div
                v-if="listSwitch"
                :key="item.id"
                :style="{ width: item.widthPosition + 'px', height: item.heightPosition + 'px', transform: 'rotateZ(' + item.rotate + 'deg)', left: item.leftPosition + 'px', top: item.topPosition + 'px', zIndex: 110 }"
                class="range"
              >
                <!-- 基站位置 -->
                <!-- <div
                  :style="{ left: (item.maxDist / 2) + 'px', top: (item.maxDist / 2) + 'px' }"
                  :title="`基站名称: ${item.name}; 区域: ${item.scro}; 坐标X: ${item.x}; 坐标Y: ${item.y}; 基站类型: ${item.jztype === 1 ? '进基站' : item.jztype === 2 ? '出基站' : '其他基站' }; 是否是考勤机站: ${item.status ? '是': '否'}`"
                  class="up"
                >
                  <img :src="item.url" alt="基站" />
                </div>-->

                <!-- 施工队员位置 -->
                <el-popover
                  v-if="prople.deviceId === item.deviceId"
                  placement="top-start"
                  class="people"
                  :style="{ transform: 'rotateZ(' + (-Number(item.rotate)) + 'deg)', left: prople.left + 'px', top: prople.top + 'px' }"
                  trigger="hover"
                >
                  <div class="labelDiv">
                    <span class="shallow">名称:</span>
                    <span class="deep">{{ prople.name }}</span>
                  </div>
                  <div class="labelDiv">
                    <span class="shallow">RFID卡:</span>
                    <span class="deep">{{ prople.rfid }}</span>
                  </div>
                  <div class="labelDiv">
                    <span class="shallow">联系方式:</span>
                    <span class="deep">{{ prople.phone }}</span>
                  </div>
                  <div class="labelDiv">
                    <span class="shallow">是否在职:</span>
                    <span class="deep">{{ prople.status ? '是' : '否' }}</span>
                  </div>
                  <div v-if="prople.plateNumber" class="labelDiv">
                    <span class="shallow">车牌号:</span>
                    <span class="deep">{{ prople.plateNumber }}</span>
                  </div>
                  <img slot="reference" :src="prople.url" alt="施工队员" />
                </el-popover>
              </div>
            </template>
          </div>
        </div>
      </template>
    </PageList>
  </div>
</template>
<script>
  import { assetsImages } from '@/utils/images'
  import listMixin from '@/mixins/list'
  import ListFilter from '@/components/ListFilter'
  import { path, baseStation, tunnel, parameter } from '@/api/api'
  import { localhostUrl, imgUrl } from '@/utils/setUrl.js'
  import { parseTime } from '@/utils/index.js'
  export default {
    components: { ListFilter },
    mixins: [listMixin],
    data() {
      return {
        listSwitch: false,
        imgSrc: '',
        distArr: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18],
        prople: {
          deviceId: '',
          top: null,
          createdTime: 0
        },
        arr: [],
        // 基站数组
        baseStationList: [],
        // 定时器
        timeID: null,
        // 开关
        sliderSwaitch: false,
        // 开关
        clickSwaitch: false,
        // 总时长(秒)
        duration: 10,
        // 得到一个数据的位置
        flag: 0,
        // 进度条数值
        value: [0, 100],
        // 保存所有位置数据
        listAry: [],
        // 搜索内容
        topFilter: {
          rfid: { label: 'RFID', placeholder: '请输入人员RFID或车辆RFID' },
          'employee.accessCardID': { label: '门禁ID', placeholder: '请输入门禁ID' },
          'car.plateNumber': { label: '车牌号', placeholder: '请输入车牌号' },
          'employee.name': { label: '员工姓名', placeholder: '请输入员工姓名' },
          // createdTime: { label: '时间', placeholder: '请选择时间', type: 'date', arr: ['createdTime', 'createdTime'] }
          createdTime: { label: '时间', placeholder: '请选择时间', type: 'dateTwo', arr: ['createdTime', 'createdTime'] }
        },
        keyList: [
          'RFID'
        ],
        iconData: [
          { name: 'BaseStationImage', value: assetsImages.baseStation, id: null }, // 基站
          { name: 'PeopleImage', value: assetsImages.people, id: null }, // 人员
          { name: 'CarImage', value: assetsImages.people, id: null } // 车辆
        ]
      }
    },
    watch: {
      value: function (newValue, oldValue) {
        if (newValue.push) {
          return
        }
        // 每秒走多少
        let item = 100 / this.duration
        // 当前位置的秒数
        let merchant = parseInt(Number(newValue) / parseInt(item))
        // 共有多少条数据
        let len = this.listAry.length
        // 得出每秒走多少条数据
        let distanceNum = Math.ceil(len / this.duration)
        // 得到当前位置
        this.flag = merchant * distanceNum
        if (this.flag >= len) {
          this.flag = len - 1
        }
        // 得到下一秒的数据
        let obj = this.listAry[this.flag]

        if (!obj) {
          return
        }
        // 取值
        this.prople = {
          deviceId: obj.deviceId,
          createdTime: obj.createdTime,
          top: obj.top,
          left: obj.left,
          rfid: obj.rfid,
          name: obj.name,
          phone: obj.phone,
          status: obj.status,
          url: obj.itemUrl,
          plateNumber: obj.plateNumber
        }
      }
    },
    mounted() {
      let that = this
      // this.getTunnelData()
      this.getMap()
      // 获取按钮
      let slider = document.querySelector('.el-slider__button-wrapper')
      let runway = document.querySelector('.el-slider__runway')
      runway.onmousedown = function () {
        that.sliderSwaitch = true
      }
      // 鼠标按下事件
      slider.onmousedown = function () {
        that.sliderSwaitch = true
        // 先清除一下定时器的值
        clearInterval(that.timeID)
      }
      // 鼠标放开事件
      window.onmouseup = function (event) {
        // 点击了播放才能播放
        if (that.sliderSwaitch && that.clickSwaitch) {
          that.time()
          that.sliderSwaitch = false
        }
      }
    },
    beforeDestroy() {
      clearInterval(this.timeID)
    },
    methods: {
      resetHandle() {
        this.baseStationList = []
        this.listAry = []
        this.handleReset({})
      },
      // 时间修改
      timeValueHandler(event) {
        if (event > this.listAry.length) {
          this.duration = this.listAry.length
        }
      },
      // 重新播放
      resetPlayHandler() {
        this.value = 0
        this.flag = 0
        // 得到下一秒的数据
        let obj = this.listAry[this.flag]
        // 取值
        this.prople = {
          deviceId: obj.deviceId,
          createdTime: obj.createdTime,
          top: obj.top,
          left: obj.left,
          rfid: obj.rfid,
          name: obj.name,
          phone: obj.phone,
          status: obj.status,
          url: obj.itemUrl,
          plateNumber: obj.plateNumber
        }
        this.time()
      },
      // 播放
      time() {
        // 点击时打开开关
        this.clickSwaitch = true
        // 进度条每秒走多少
        let secondNumber = Number(100 / this.duration)

        if (this.timeID) {
          // 先清除一下定时器的值
          clearInterval(this.timeID)
          // 再创建一下
          this.timeID = null
        }

        // 开启定时器
        this.timeID = setInterval(() => {
          if (this.value + secondNumber >= 100) {
            // 进度条到最后位置
            this.value = 100
            // 清除定时器
            clearInterval(this.timeID)
            // 关闭开关
            this.clickSwaitch = false
          } else {
            // 进度条进度
            this.value = Number(this.value) + secondNumber
          }
        }, 1000)
      },
      // 暂停
      suspendHandler() {
        clearInterval(this.timeID)
        this.clickSwaitch = false
      },
      // 停止
      stopHandler() {
        clearInterval(this.timeID)
        this.value = 0
        this.flag = 0
        // 得到下一秒的数据
        let obj = this.listAry[this.flag]
        // 取值
        this.prople = {
          deviceId: obj.deviceId,
          createdTime: obj.createdTime,
          top: obj.top,
          left: obj.left,
          rfid: obj.rfid,
          name: obj.name,
          phone: obj.phone,
          status: obj.status,
          url: obj.itemUrl,
          plateNumber: obj.plateNumber
        }
        this.clickSwaitch = false
      },
      // 生成坐标数组
      getListHandler() {
        this.baseStationList.forEach((item, index) => {
          // 得到需要的信息,保存到基站数据中
          item.arr = this.distArr.map(coordinate => {
            return {
              id: coordinate,
              createdTime: item.createdTime,
              deviceId: item.deviceId,
              rfid: item.rfid,
              name: item.propleName,
              phone: item.phone,
              status: item.propleStatus,
              left: this.random(0, Number(item.widthPosition)),
              top: this.random(0, Number(item.heightPosition)),
              url: item.url,
              itemUrl: item.itemUrl,
              plateNumber: item.plateNumber
            }
          })
        })
        // 保存所有位置数据
        this.listAry = []

        // 临时数组
        let arrList = []
        // 尽量减少重复进入作用域
        let list = this.baseStationList

        for (let i = 0; i < list.length; i++) {
          let arr = list[i].arr
          for (let j = 0; j < arr.length; j++) {
            // 循环得到所有数据
            arrList.push(arr[j])
          }
        }
        // 获取数据
        this.listAry = JSON.parse(JSON.stringify(arrList))

        // 设置进度条长度（进度条长度最大可能只能到100）
        this.value = 0

        // 得到下一秒的数据
        let obj = this.listAry[0]
        // 取值
        this.prople = {
          deviceId: obj.deviceId,
          createdTime: obj.createdTime,
          rfid: obj.rfid,
          name: obj.name,
          phone: obj.phone,
          status: obj.status,
          top: obj.top,
          left: obj.left,
          url: obj.itemUrl,
          plateNumber: obj.plateNumber
        }
      },
      // 取随机数
      random(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min)
      },
      // 基站图片
      async getBaseStationImage() {
        try {
          let res = await parameter('get', { parameterName: 'BaseStationImage' })
          if (res.code === 200) {
            this.iconData[0].value = res.data.value
            // this.iconData[0].id = res.data.id
          }
        } catch (err) {
          // 基站图片
          this.iconData[0].value = assetsImages.baseStation
          // this.$message.error('基站图标查询失败，已使用默认图标！')
        }
      },
      // 人员图片
      async getPeopleImage() {
        try {
          let res = await parameter('get', { parameterName: 'PeopleImage' })
          if (res.code === 200) {
            this.iconData[1].value = res.data.value
            // this.iconData[1].id = res.data.id
          }
        } catch (err) {
          // 施工队员图片
          this.iconData[1].value = assetsImages.people
        }
      },
      // 车辆图片
      async getCarImage() {
        try {
          let res = await parameter('get', { parameterName: 'CarImage' })
          if (res.code === 200) {
            this.iconData[2].value = res.data.value
            // this.iconData[2].id = res.data.id
          }
        } catch (err) {
          // 车辆图片
          this.iconData[2].value = assetsImages.car
        }
      },
      // 获取图标
      // async getTunnelData() {
        // this.getBaseStationImage()
        // this.getPeopleImage()
        // this.getCarImage()
      // },
      // 请求列表数据
      async getList(query) {
        if (query.search && query.search.length > 0) {
          this.listSwitch = true
          let valueItem = null
          let inde = 0
          let flag = false
          query.search.forEach((item, ind) => {
            if (item.key === 'createdTime') {
              valueItem = item.value
              flag = true
              inde = ind
              item.value = item.value + ' 00:00:00'
              item.operation = 4
              item.sequence = 1
              item.relationship = 0
            }
          })
          if (flag) {
            let objOne = {
              key: "createdTime",
              value: valueItem + ' 23:59:59',
              operation: 5,
              sequence: 2,
              relationship: 0
            }
            query.search.splice(inde + 1, 0, objOne)
          }
        } else {
          this.listSwitch = false
          return
        }
        query.pageSize = 1e8
        console.log(query)
        var find = query.search.find(r => r.key == 'rfid')
        if (find) {
          query.search.splice(query.search.indexOf(find), 1)
          query.search.push(Object.assign({ ...find }, { key: 'employee.rfid' }))
          query.search.push(Object.assign({ ...find }, { key: 'car.rfid', relationship: 1 }))
        }

        this.tableLoading = true
        let that = this
        try {
          const { code, data: { items: resData, count, pageIndex } } = await path('post', query, false)
          if (resData.length === 0) {
            return this.$message.warning('未查到该员工轨迹记录！')
          }
          // if (code === 10) {
          //   return this.$message.warning('有重名员工，请输入rfid重新查询')
          // }
          console.log(resData)
          let ary = []
          resData.reverse().forEach((item, index) => {
            if (item.baseStation) {
              ary.push({
                id: index,
                index: 'name' + index,
                createdTime: parseTime(new Date(item.createdTime), '{y}-{m}-{d} {h}:{i}'),
                name: item.baseStation ? item.baseStation.name : '',
                scro: !item.baseStation ? '' : item.baseStation.area ? item.baseStation.area.name : '',
                jztype: item.baseStation ? item.baseStation.siteType : '',
                status: item.baseStation ? item.baseStation.isForWorkCheck : '',
                x: item.baseStation ? item.baseStation.xPosition : '',
                y: item.baseStation ? item.baseStation.yPosition : '',
                deviceId: item.baseStation ? item.baseStation.deviceId : '',
                rfid: item.carId ? item.car.rfid : item.employee.rfid,
                plateNumber: item.carId ? item.car.plateNumber : item.employee.plateNumber,
                propleName: item.carId ? item.car.carType : item.employee.name,
                phone: item.carId ? item.car.responsiblePhone : item.employee.phone,
                propleStatus: item.carId ? 1 : item.employee.status,
                url: that.iconData[0].value,
                itemUrl: item.carId ? that.iconData[2].value : that.iconData[1].value,
                maxDist: '',
                arr: [],
                widthPosition: item.baseStation ? item.baseStation.widthPosition : '',
                heightPosition: item.baseStation ? item.baseStation.heightPosition : '',
                leftPosition: item.baseStation ? item.baseStation.leftPosition : '',
                topPosition: item.baseStation ? item.baseStation.topPosition : '',
                rotate: item.baseStation ? item.baseStation.rotate : '',
              })
            }
          })
          this.baseStationList = JSON.parse(JSON.stringify(ary))

          this.getListHandler()
        } catch (err) {
          this.tableLoading = false
        }
      },
      // 请求地图
      async getMap() {
        try {
          let obj = { id: 1 }
          let res = await tunnel('get', obj, true)
          if (res.code === 200) {
            if (res.data.backedImageName) {
              this.imgSrc = imgUrl + '/' + res.data.backedImageName
            } else {
              if (res.data.templateName === '单洞') {
                this.imgSrc = assetsImages.singleHole
              } else if (res.data.templateName === '双洞') {
                this.imgSrc = assetsImages.doubleHole
              } else {
                this.imgSrc = assetsImages.singleHole
              }
            }
          }
        } catch (err) {
          let er = err
          // this.$message.error('数据查询失败！')
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .labelDiv {
    display: flex;
    .deep {
      color: #000;
      width: 120px;
      text-align: left;
    }
    .shallow {
      padding-right: 10px;
      color: #666;
      width: 70px;
      text-align: right;
    }
  }
  .sc-list-filter-col {
    width: auto;
  }
  .tips {
    display: flex;
    padding-bottom: 20px;
  }
  .divOne {
    margin: 0 auto;
    width: 1202px;
    height: 619px;
    display: flex;
    position: relative;
    border: 1px solid #ccc;
    background-color: #ccc;
    .mapImg {
      width: 100%;
      height: 100%;
    }
    .up {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      position: absolute;
      display: inline-block;
      background-color: #fff;
      transform: translate(-50%, -50%);
      img {
        float: left;
        width: 100%;
        height: 100%;
      }
    }
    .range {
      display: inline-block;
      position: absolute;
      // border: 1px solid lime;
      .up {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        position: absolute;
        display: inline-block;
        background-color: #fff;
        transform: translate(-50%, -50%);
        img {
          float: left;
          width: 100%;
          height: 100%;
        }
        // transform: rotateX(120deg) translateZ(220px) translateX(364PX);
        // .baseStation {
        // width: 60px;
        // height: 50px;
        // text-align: center;
        // line-height: 50px;
        // position: absolute;
        // background-color: #53868B;
        // transform: rotateX(180deg);
        // }
      }
      .people {
        width: 20px;
        height: 20px;
        position: absolute;
        border-radius: 50%;
        background-color: #fff;
        display: inline-block;
        transform: translate(-50%, -50%);
        img {
          width: 100%;
          height: 100%;
          float: left;
        }
      }
    }
  }
</style>
